# -*- coding: utf-8 -*-

import math
from django.core import serializers
import re
from django.http import HttpResponse, JsonResponse
import os
from pathlib import Path
from mysqlModel.models import data
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def postData(req):
    if req.method == "POST":
        try:
            version = req.POST['version']
            if not version:
                return JsonResponse({'status': False, 'messages': '没有可用的版本号，请前往"版本控制"板块添加'})
            cpu = req.POST['cpu']
            email = req.POST['email']
            if not email:
                return JsonResponse({'status': False, 'messages': '未填邮箱'})
            if not re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", email):
                return JsonResponse({'status': False, 'messages': '邮箱格式错误'})
            # 获取上传的文件，如果没有则为None
            myFile = req.FILES.get("myfile", None)
            # 获取文件流，得到具体内容
            test = myFile
            content = myFile.read().decode('utf-8').splitlines()
            cust_name = [line for line in content if line.startswith('Licensee=')][0].split('=')[1]
            myFile.name = f'{cust_name}_{version}_{cpu}_{email}_license.lic'
            if data.objects.filter(license__startswith=f'{cust_name}_{version}_{cpu}_'):
                return JsonResponse({'status': False, 'messages': '数据库中已经存在相同的license\n请若要保存新的license，请先删除原来的license！！'})
            # 将获取到的上传文件，保存到项目目录下
            BASE_DIR = Path(__file__).resolve().parent.parent

            dir_name = os.path.join(BASE_DIR, "upload")
            if not os.path.exists(dir_name):
                os.makedirs(dir_name)
            with open(os.path.join(dir_name, myFile.name), "wb+") as f:
                for chunk in myFile.chunks():
                    f.write(chunk)
            test1 = data(name=cust_name, soft_version=version, cpu=cpu, license=myFile, email=email)
            test1.save()

            return JsonResponse({'status': True, 'messages': 'license上传成功\n后台已开始构建安装包，完毕后将发送邮件至您的邮箱，请等待~'})

        except Exception as ex:
            print(ex,'######################')
            if str(ex) == "'NoneType' object has no attribute 'read'":
                return JsonResponse({'status': False, 'messages': '没有上传文件'})
            elif str(ex) == 'list index out of range':
                return JsonResponse({'status': False, 'messages': '文件格式不为lic'})
            else:
                return JsonResponse({'status': False, 'messages': '请求失败！！'})

    return HttpResponse(req)


# 获取数据
def getData(request):
    # 初始化
    response = ""
    response1 = []

    # 通过objects这个模型管理器的all()倒序获得所有数据行，相当于SQL中的SELECT * FROM
    # list = data.objects.all().order_by('-id')
    # list = list[::-1]
    # filter相当于SQL中的WHERE，可设置条件过滤结果
    # response2 = data.objects.filter(id=1)

    # 获取单个对象
    # response3 = data.objects.get(id=1)

    # 限制返回的数据 相当于 SQL 中的 OFFSET 0 LIMIT 2;
    # data.objects.order_by('name')[0:2]

    # 数据排序
    # data.objects.order_by("id")

    # 上面的方法可以连锁使用
    # data.objects.filter(name="runoob").order_by("id")

    # 输出所有数据
    pageNum = int(request.GET.get('pageNum', default='1'))
    pageSize = int(request.GET.get('pageSize', default='10'))
    query = request.GET.get('query')
    if query:
        lst = data.objects.filter(name__contains=query)
    else:
        lst = data.objects.all().order_by('-id')
    mylist = lst[(pageNum - 1) * pageSize: pageSize * pageNum]

    mydata = serializers.serialize("json", mylist)
    # print(mydata,'json序列化')
    return JsonResponse({'total': math.ceil(len(lst) / pageSize), 'data': mydata}, status=200)


# 更新数据
def upData(request):
    # 修改其中一个id=1的name字段，再save，相当于SQL中的UPDATE
    test1 = data.objects.get(id=1)
    test1.name = 'Google'
    test1.save()

    # 另外一种方式
    # data.objects.filter(id=1).update(name='Google')

    # 修改所有的列
    # data.objects.all().update(name='Google')

    return HttpResponse("<p>修改成功</p>")


# 删除数据
@csrf_exempt
def deleteData(request):
    if request.POST['type'] == 'del':
        # 删除id=1的数据
        dataofdelete = data.objects.get(id=request.POST['rid'])
        # 获得文件目录
        BASE_DIR = Path(__file__).resolve().parent.parent
        # 获得license文件夹
        dir_name = os.path.join(BASE_DIR, "upload")
        # 获得license具体文件
        file_path = os.path.join(dir_name, dataofdelete.license)
        dataofdelete.delete()
        try:
            os.remove(file_path)
        except Exception:
            return JsonResponse({'status': False, 'messages': '数据库中这条数据删除成功！\n但是文件夹中没有这个文件'})
    if request.POST['type'] == 're':
        dataofre = data.objects.filter(id=request.POST['rid'])
        dataofre.update(lic_md5='')
        return JsonResponse({'status': True, 'messages': '重新打包成功\n后台已开始构建安装包，完毕后将发送邮件至您的邮箱，请等待~'})
    # 另外一种方式
    # data.objects.filter(id=1).delete()

    # 删除所有数据
    # data.objects.all().delete()

    return JsonResponse({'status': False, 'messages': '数据请求失败！'})
